const router = require("koa-router")()
const { login, userlist, updateaddlist, dellist, register, updateUserList } = require("../controller/user")
const { successModel, errorModel } = require("../utils/stateModel")
const SECRET = process.env.JWT_SECRET
const Role = require('../db/models/roleSchema')
const jwt = require("jsonwebtoken")
router.prefix('/api/user')

router.post('/login', async (ctx, next) => {
  // const { username, password } = ctx.request.body
  const userList = await login(ctx.request.body)
  // async function delay(time) {
  //     return new Promise(function(resolve, reject) {
  //       setTimeout(function(){
  //         resolve();
  //       }, time);
  //     });
  //   };
  //   await delay(2000);
  if (!userList) {
    ctx.body = new errorModel('用户名或密码错误', '1001')
    return
  }
  const roleList = await Role.find({ _id: userList.roleNames })
  // console.log("xxx",roleList)
  //按钮权限返回
  let permSign = []
  if (roleList.length) {
    for (let i in roleList) {
      permSign = permSign.concat(roleList[i].permSign)
    }
  }
  //jwt设置token返回前端
  const token = jwt.sign({ userList }, SECRET, { expiresIn: "1h" })
  ctx.body = new successModel({ token, permSign, userInfo: userList })
})

// 用户管理模块
router.post('/userlist', async (ctx, next) => {
  const { username, mobile, pageNum } = ctx.query
  const { userList, total } = await userlist(username, mobile, pageNum)

  if (!userList) {
    ctx.body = new errorModel('用户名或密码错误', '1001')
    return
  }
  ctx.body = new successModel({ userList, total })
})

// 删除用户列表中数据
router.post('/deleteUserList', async (ctx, next) => {
  await dellist(ctx, ctx.request.body)
})

router.post('/updateUserList', async (ctx, next) => {
  await updateUserList(ctx, ctx.request.body)
})

//编辑、新增
router.post('/updateaddlist', async (ctx, next) => {
  await updateaddlist(ctx, ctx.request.body)
})

//删除
router.post('/dellist', async (ctx, next) => {
  await dellist(ctx, ctx.request.body)
})

// 注册
router.post('/register', async (ctx, next) => {
  await register(ctx, ctx.request.body)
})

module.exports = router